import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
import QtQuick.Dialogs 1.3
import QtLocation 5.12
import QtPositioning 5.12
import QtQuick.Shapes 1.12

Window {
    width: 800
    height: 600
    visible: true
    title: qsTr("YCLocation - 路线规划")

    Component.onCompleted: {
        console.log(_map.supportedMapTypes[0].name)
        _map.activeMapType = _map.supportedMapTypes[0]
    }

    // 路线站点管理
    property var waypoints: []  // 格式: [{lat, lng, type: "start"/"waypoint"/"end"}, ...]
    property var routePath: []  // 路线路径数据
    property bool routeMode: false  // 路线规划模式

     Map {
        id: _map
        anchors.fill: parent
        gesture.acceptedGestures:   MapGestureArea.PinchGesture | MapGestureArea.PanGesture | MapGestureArea.FlickGesture
        gesture.flickDeceleration:  3000
        minimumZoomLevel: 3
        maximumZoomLevel: 20
        zoomLevel: 10
        center: QtPositioning.coordinate(30.67, 104.06) // 成都位置
        plugin: Plugin { 
            name: "YCLocationProvider"
        }

        // 点击地图获取经纬度
        MouseArea {
            anchors.fill: parent
            onClicked: {
                if (!routeMode) return
                
                // 将屏幕坐标转换为地理坐标（经纬度）
                var coordinate = _map.toCoordinate(Qt.point(mouse.x, mouse.y))
                console.log("点击坐标：", coordinate.latitude, coordinate.longitude)
                
                // 显示经纬度并弹出确认对话框
                addWaypointDialog.coordinate = coordinate
                addWaypointDialog.open()
            }
        }

        // 使用Canvas绘制站点和路线
        Canvas {
            id: routeCanvas
            anchors.fill: parent
            
            onPaint: {
                var ctx = getContext("2d")
                ctx.clearRect(0, 0, width, height)
                
                // 绘制路线
                if (routePath.length > 1) {
                    // 使用路线规划的结果
                    ctx.strokeStyle = "blue"
                    ctx.lineWidth = 4
                    ctx.beginPath()
                    
                    for (var i = 0; i < routePath.length; i++) {
                        var point = _map.fromCoordinate(QtPositioning.coordinate(routePath[i].lat, routePath[i].lng))
                        if (i === 0) {
                            ctx.moveTo(point.x, point.y)
                        } else {
                            ctx.lineTo(point.x, point.y)
                        }
                    }
                    ctx.stroke()
                } else if (waypoints.length > 1) {
                    // 如果没有路线规划结果，使用站点之间的直线连接
                    ctx.strokeStyle = "blue"
                    ctx.lineWidth = 3
                    ctx.setLineDash([5, 5])  // 虚线样式
                    ctx.beginPath()
                    
                    // 按站点类型排序：起点 -> 途经点 -> 终点
                    var sortedWaypoints = []
                    var startPoint = waypoints.find(function(w) { return w.type === "start" })
                    var endPoint = waypoints.find(function(w) { return w.type === "end" })
                    var waypointList = waypoints.filter(function(w) { return w.type === "waypoint" })
                    
                    if (startPoint) sortedWaypoints.push(startPoint)
                    sortedWaypoints = sortedWaypoints.concat(waypointList)
                    if (endPoint) sortedWaypoints.push(endPoint)
                    
                    for (var k = 0; k < sortedWaypoints.length; k++) {
                        var wpPoint = _map.fromCoordinate(QtPositioning.coordinate(sortedWaypoints[k].lat, sortedWaypoints[k].lng))
                        if (k === 0) {
                            ctx.moveTo(wpPoint.x, wpPoint.y)
                        } else {
                            ctx.lineTo(wpPoint.x, wpPoint.y)
                        }
                    }
                    ctx.stroke()
                    ctx.setLineDash([])  // 重置虚线样式
                }
                
                // 绘制站点
                for (var j = 0; j < waypoints.length; j++) {
                    var wp = waypoints[j]
                    var wpPoint = _map.fromCoordinate(QtPositioning.coordinate(wp.lat, wp.lng))
                    
                    // 设置站点颜色
                    var color = wp.type === "start" ? "green" :
                               wp.type === "end" ? "red" : "blue"
                    
                    // 绘制圆形站点
                    ctx.fillStyle = color
                    ctx.strokeStyle = "white"
                    ctx.lineWidth = 2
                    ctx.beginPath()
                    ctx.arc(wpPoint.x, wpPoint.y, 16, 0, 2 * Math.PI)
                    ctx.fill()
                    ctx.stroke()
                    
                    // 绘制站点文字
                    ctx.fillStyle = "white"
                    ctx.font = "bold 14px Arial"
                    ctx.textAlign = "center"
                    ctx.textBaseline = "middle"
                    var text = wp.type === "start" ? "S" :
                              wp.type === "end" ? "E" : "W"
                    ctx.fillText(text, wpPoint.x, wpPoint.y)
                }
            }
            
            // 当地图移动或缩放时重新绘制
            Connections {
                target: _map
                onCenterChanged: routeCanvas.requestPaint()
                onZoomLevelChanged: routeCanvas.requestPaint()
            }
        }
    }

    // 添加站点的确认对话框
    Dialog {
        id: addWaypointDialog
        property var coordinate: null
        title: "添加站点"
        width: 300
        height: 200
        
        contentItem: Column {
            spacing: 10
            anchors.fill: parent
            
            Text {
                text: coordinate ? `经纬度：${coordinate.latitude.toFixed(6)}, ${coordinate.longitude.toFixed(6)}` : ""
                wrapMode: Text.WordWrap
                width: parent.width
            }
            
            Button {
                text: "设为起点"
                width: parent.width
                onClicked: {
                    // 清空已有起点，添加新起点
                    waypoints = waypoints.filter(function(w) { return w.type !== "start" })
                    var newWaypoint = {
                        lat: addWaypointDialog.coordinate.latitude,
                        lng: addWaypointDialog.coordinate.longitude,
                        type: "start"
                    }
                    waypoints.push(newWaypoint)
                    console.log("添加起点:", newWaypoint)
                    console.log("当前站点数量:", waypoints.length)
                    routeCanvas.requestPaint()  // 重新绘制Canvas
                    addWaypointDialog.close()
                }
            }
            
            Button {
                text: "添加途经点"
                width: parent.width
                onClicked: {
                    var newWaypoint = {
                        lat: addWaypointDialog.coordinate.latitude,
                        lng: addWaypointDialog.coordinate.longitude,
                        type: "waypoint"
                    }
                    waypoints.push(newWaypoint)
                    console.log("添加途经点:", newWaypoint)
                    console.log("当前站点数量:", waypoints.length)
                    routeCanvas.requestPaint()  // 重新绘制Canvas
                    addWaypointDialog.close()
                }
            }
            
            Button {
                text: "设为终点"
                width: parent.width
                onClicked: {
                    waypoints = waypoints.filter(function(w) { return w.type !== "end" })
                    var newWaypoint = {
                        lat: addWaypointDialog.coordinate.latitude,
                        lng: addWaypointDialog.coordinate.longitude,
                        type: "end"
                    }
                    waypoints.push(newWaypoint)
                    console.log("添加终点:", newWaypoint)
                    console.log("当前站点数量:", waypoints.length)
                    routeCanvas.requestPaint()  // 重新绘制Canvas
                    addWaypointDialog.close()
                }
            }
            
            Button {
                text: "取消"
                width: parent.width
                onClicked: addWaypointDialog.close()
            }
        }
    }

    // 控制面板
    Rectangle {
        id: controlPanel
        width: 200
        height: 300
        anchors.right: parent.right
        anchors.top: parent.top
        anchors.margins: 10
        color: "white"
        border.color: "gray"
        border.width: 1
        radius: 5
        
        Column {
            anchors.fill: parent
            anchors.margins: 10
            spacing: 10
            
            Text {
                text: "路线规划控制"
                font.bold: true
                font.pixelSize: 14
            }
            
            Button {
                text: routeMode ? "退出路线模式" : "进入路线模式"
                width: parent.width
                onClicked: {
                    routeMode = !routeMode
                    if (!routeMode) {
                        // 退出路线模式时清除所有站点和路线
                        waypoints = []
                        routePath = []
                        routeCanvas.requestPaint()
                    }
                }
            }
            
            Text {
                text: "当前站点: " + waypoints.length
                font.pixelSize: 12
            }
            
            Button {
                text: "规划路线"
                width: parent.width
                enabled: routeMode && waypoints.length >= 2
                onClicked: {
                    var startCount = waypoints.filter(function(w) { return w.type === "start" }).length
                    var endCount = waypoints.filter(function(w) { return w.type === "end" }).length
                    
                    if (startCount === 0 || endCount === 0) {
                        console.log("请设置起点和终点")
                        return
                    }
                    
                    // 按顺序整理站点（起点->途经点->终点）
                    var start = waypoints.find(function(w) { return w.type === "start" })
                    var waypointList = waypoints.filter(function(w) { return w.type === "waypoint" })
                    var end = waypoints.find(function(w) { return w.type === "end" })
                    var orderedPoints = [start].concat(waypointList).concat([end])
                    
                    // 调用后端路线服务
                    if (typeof routeService !== 'undefined') {
                        routeService.requestRoute(orderedPoints)
                    } else {
                        console.log("路线服务未初始化")
                    }
                }
            }
            
            Button {
                text: "测试路线规划结果"
                width: parent.width
                onClicked: {
                    // 创建测试路线数据
                    routePath = [
                        {lat: 30.678180944311322, lng: 104.04098372632876},
                        {lat: 30.668975831911805, lng: 104.05989718980834},
                        {lat: 30.65621385507812, lng: 104.04534401581088}
                    ]
                    console.log("设置测试路线，点数:", routePath.length)
                    routeCanvas.requestPaint()
                }
            }
            
            ComboBox {
                id: providerComboBox
                width: parent.width
                model: ["osm", "google", "bing"]
                currentIndex: 0
                onCurrentTextChanged: {
                    if (typeof routeService !== 'undefined') {
                        routeService.setRouteProvider(currentText)
                    }
                }
            }
            
            Text {
                text: "路线服务: " + (providerComboBox.currentText || "osm")
                font.pixelSize: 10
            }
            
            Button {
                text: "清除路线"
                width: parent.width
                onClicked: {
                    waypoints = []
                    routePath = []
                    routeCanvas.requestPaint()  // 重新绘制Canvas
                }
            }
        }
    }

    // 连接路线服务信号
    Connections {
        target: typeof routeService !== 'undefined' ? routeService : null
        onRouteReady: {
            // 将后端返回的经纬度列表转换为路线路径格式
            routePath = []
            for (var i = 0; i < arguments[0].length; i++) {
                var coord = arguments[0][i]
                routePath.push({
                    lat: coord.lat,
                    lng: coord.lng
                })
            }
            routeCanvas.requestPaint()  // 重新绘制Canvas
            console.log("路线绘制完成，共", routePath.length, "个点")
        }
        
        onRouteError: {
            console.log("路线规划错误:", arguments[0])
        }
        
        onRouteProgress: {
            console.log("路线规划进度:", arguments[0] + "%")
        }
    }
}